<?php
declare (strict_types = 1);

namespace app\middleware;

use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Validate;

class ValidateParams
{
    public function handle($request, \Closure $next, ?string $scene = null)
    {
        // 如果没有指定场景，直接放行
        if ($scene === null) {
            return $next($request);
        }
        [$module,$scene] = explode('.', $scene,2);
        $validateConfig = config("validate.{$module}.{$scene}");
        
        if (!$validateConfig) {
            throw new \RuntimeException("验证场景 validate.{$module}.{$scene} 未配置");
        }
        //dump($validateConfig);
        $rules = $validateConfig['rules'] ?? [];
        $messages = $validateConfig['message'] ?? [];

        $validator = Validate::rule($rules)->message($messages);
        if (!$validator->check($request->param())) {
            throw new ValidateException($validator->getError());
        }

        return $next($request);
    }
}
